package cn.cvs.controller;

import cn.cvs.pojo.Fruit;
import cn.cvs.service.FruitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class FruitController {
    @Autowired
    private FruitService fruitService;

    @GetMapping(value = "/list")
    public String list(Model model,@RequestParam(required = false) String type,@RequestParam(required = false) String breed,@RequestParam(defaultValue = "1") Integer pageIndex){
        Integer pageSize=5;
        int count=fruitService.count(type, breed);
        int pageNum=(count%pageSize)==0?(count/pageSize):(count/pageSize)+1;
        model.addAttribute("count",count);
        model.addAttribute("pageIndex",pageIndex);
        model.addAttribute("pageNum",pageNum);
        List<Fruit> list = fruitService.getlist(type,breed,pageIndex,pageSize);
        model.addAttribute("type",type);
        model.addAttribute("breed",breed);
        model.addAttribute("list",list);
        return "list";
    }

    @GetMapping(value = "/view")
    public String view(Model model,Integer id){
        Fruit fruit = fruitService.selectById(id);
        model.addAttribute("fruit",fruit);
        return "view";
    }
    //@ResponseBody 将返回的内容放入响应提中
    @ResponseBody
    @GetMapping(value = "/delete")
    public String del(Integer id){
        int result = fruitService.delete(id);
        if (result>0) {
            //删除成功，相应success字符串出去
            return "success";
        }
        return "error";
    }

    @ResponseBody
    @PostMapping(value = "/add")
    public String add(Fruit fruit){
        int result = fruitService.add(fruit);
        if (result>0){
            return "<script>alert('新增成功');location.href='list';</script>";
        }
        return "<script>alert('新增失败');history.back();</script>";
    }

    @GetMapping(value = "/upd")
    public String upd(Model model,Integer id){
        Fruit fruit = fruitService.selectById(id);
        model.addAttribute(fruit);
        return "upd";
    }

    @ResponseBody
    @PostMapping(value = "/upd1")
    public String upd1(Fruit fruit){
        int result = fruitService.upd(fruit);
        if (result > 0) {
            return "<script>alert('修改成功');location.href='list';</script>";
        }
        return "<script>alert('修改失败');history.back();</script>";
    }


}
